<html>
  <head>
    <meta charset="utf-8">
    <title>Mongoose ODM</title>
    <style>
      body {
        background: url('/docs/2.7.x/images/bg.png');
        padding: 0 30px 30px;
        margin-top: 0;
      }

      #wrap {
        background: url('/docs/2.7.x/images/pattern.png') no-repeat -134px -211px;
        min-height: 600px;
        padding-top: 30px;
      }

      #page {
        width: 650px;
        margin: auto;
        position: relative;
      }

      #footer {
        font: 13px Helvetica;
        padding-top: 15px;
        border-top: 1px solid #000;
        color: #666;
        margin-top: 25px;
      }

      #footer > div {
        padding-top: 8px;
        float: right;
        text-align: right;
        padding-bottom: 20px;
      }

      #content {
        color: #111;
        font: 15px Courier;
      }

      #content h1, #content h2, #content h3 {
        text-shadow: 0 1px 0 #fff;
      }

      #announce {
        background: #2A758A;
        border: 10px solid black;
        border-radius: 7px;
        padding: 30px;
        font-size: 125%;
        color: white;
        text-shadow: none;
        font-family: Arial;
      }

      #announce a {
        color: orange;
        text-shadow: none;
      }

      pre {
        background: rgba(255,255,255,.8);
        border: 1px solid #c6c6c6;
        padding: 10px;
        border-radius: 3px;
        box-shadow: 1px 3px 6px #ddd;
      }

      code {
        background: rgba(255,255,255,.8);
        border: 1px solid #c6c6c6;
        color: #333;
        border-radius: 3px
      }

      pre code {
        border: 0 none;
      }

      form {
        font: bold 12px Helvetica;
        text-shadow: 0 1px 0 #fff;
        float: left;
        padding-bottom: 25px;
      }

      form img {
        margin-right: 5px
      }

      #google-members-count {
        vertical-align: top;
        line-height: 32px;
      }

      h1 a {
        background: url('/docs/2.7.x/images/logo.png');
        width: 404px;
        height: 47px;
        margin-bottom: 40px;
        text-indent: -500em;
        display: block;
      }

      a {
        color: #2a758a;
        text-shadow: 0 1px 0 #fff;
        text-decoration: none;
      }

      a:hover {
        opacity: 0.8;
      }

      #menu {
        position: fixed;
        top: 0;
        left: 0;
        height: 100%;
        background-color: rgba(0,0,0,0.3);
        font: bold 15px Helvetica;
        border-right: 1px solid rgba(0,0,0,0.2);
      }

      #menu ul {
        margin: 0;
        padding: 50px 0;
      }

      #menu ul li {
        list-style-type: none;
        padding-left: 15px;
        padding-right: 20px;
      }

      #menu ul li a {
        color: #fff;
        text-shadow: none;
      }
      #menu ul li a:hover {
        text-decoration: underline;
      }
      #wild { margin-top: 10px; }
    </style>

    <script>
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-1122274-9']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
      
      function getMembers(data){
        if (!(data && data.query && data.query.results && data.query.results.p)) return;
        var members = document.createElement('span');
        members.id = 'google-members-count';
        members.innerHTML = '('+ data.query.results.p +' members)';
        document.getElementsByTagName('FORM')[0].insertBefore(members, document.getElementById('google-subscribe-input'));
      };

      window.onload = function(){
        // lame jsonp
        var script = document.createElement('script');
        script.src = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fgroups.google.com%2Fgroup%2Fmongoose-orm%2Fabout%22%20and%20xpath%3D'%2F%2Fdiv%5B%40class%3D%5C'maincontbox%5C'%5D%2Ftable%2Ftr%5B1%5D%2Ftd%2Fp%5B1%5D'%0A&format=json&callback=getMembers";
        document.head.appendChild(script);
      };
    </script>
  </head>
  <body>
    <a href="http://github.com/learnboost/mongoose"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <div id="wrap">
      <div id="page">
        <div id="menu">
          <ul>
            <li><a href="../index.html">Home</a></li>
            <li><a href="model-definition.html">Models/Schemas</a></li>
            <li><a href="schematypes.html">Schema Types</a></li>
            <li><a href="schema-options.html">Schema Options</a></li>
            <li><a href="middleware.html">Middleware</a></li>
            <li><a href="finding-documents.html">Finding Docs</a></li>
            <li><a href="updating-documents.html">Updating Docs</a></li>
            <li><a href="query.html">Queries</a></li>
            <li><a href="querystream.html">Query Streams</a></li>
            <li><a href="methods-statics.html">Methods &amp; Statics</a>
            <li><a href="defaults.html">Defaults</a></li>
            <li><a href="indexes.html">Indexes</a></li>
            <li><a href="validation.html">Validation</a></li>
            <li><a href="virtuals.html">Virtuals</a></li>
            <li><a href="getters-setters.html">Getters / Setters</a></li>
            <li><a href="embedded-documents.html">Embedded Docs</a></li>
            <li><a href="populate.html">Populate (DBRef-like)</a></li>
            <li><a href="plugins.html">Plugins</a></li>
            <li><a href="errors.html">Errors</a></li>
            <li><a href="migration-1x-2x.html">v1x - v2x Migration</a></li>
            <li><a href="api.html">API</a></li>
          </ul>
        </div>

        <h1><a href="../index.html">Mongoose</a></h1>

        <div id="content">
          <!-- ANNOUNCE -->
          <h1>Defining a model</h1>

<p>Models are defined by passing a <code>Schema</code> instance to <code>mongoose.model</code>.</p>

<pre><code>mongoose.model('MyModel', mySchema);
// mySchema is &lt;a Schema&gt;
</code></pre>

<p>You can easily access the <code>Schema</code> constructor from the <code>mongoose</code> singleton:</p>

<pre><code>var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var mySchema = new Schema({
    // my props
});
</code></pre>

<p>Models are then accessed from <code>mongoose</code> if you want to use a single connection:</p>

<pre><code>// connect the `mongoose` instance
mongoose.connect('mongodb://host/db');

var BlogPost = mongoose.model('BlogPost');
</code></pre>

<p>Or from a <code>Connection</code> instance if you want to use multiple databases/connections:</p>

<pre><code>var db = mongoose.createConnection('mongodb://host/db')
  , BlogPost = db.model('BlogPost');
</code></pre>

<p><strong>Important</strong>: the actual interaction with the data happens with the <code>Model</code> that you obtain through <code>mongoose.model</code> or <code>db.model</code>. That's the object that you can instantiate or that you can call <code>.find()</code>, <code>.findOne()</code>, etc upon. Don't confuse schemas and actual models!</p>

<h2>Defining your keys</h2>

<p>The <code>Schema</code> constructor receives an object representation of your schemas as its first parameter. If you want to add more keys later, <code>Schema#add</code> provides the same functionality.</p>

<p>Your schema is constructed by passing all the JavaScript natives that you know (String, Number, Date, Buffer) as well as others exclusive to MongoDb (for example <code>Schema.ObjectId</code>). For details on all SchemaTypes see the <a href="schematypes.html">Schema Type chapter</a>.</p>

<pre><code>var ObjectId = Schema.ObjectId;

var PostSchema = new Schema({
    owner   : ObjectId
  , title   : String
  , date    : Date
});
</code></pre>

<h3>Defining documents within documents</h3>

<p>To define an array of documents that follows a certain schema, make the value an array with the schema constructor inside.</p>

<p>For example, let's assume we want to have a collection of comments within a blogpost, and we want them to be subject to casting, validation, and other functionality provided by models:</p>

<pre><code>var Comment = new Schema({
    body  : String
  , date  : Date
});

var Post = new Schema({
    title     : String
  , comments  : [Comment]
});
</code></pre>

<p>This will allow you to interact very easily with subdocuments later on. For more information, refer to the chapter on <a href="embedded-documents.html">embedded documents</a>.</p>

<h3>Defining custom options for keys</h3>

<p>Each key that you define is internally mapped to a <code>SchemaType</code>. Bear in mind, a Schema is not something that you interact directly with, but it's a way to describe to Mongoose what you want your data to look like, and how you want it to behave.</p>

<p><code>SchemaType</code>s take care of validation, casting, defaults, and other general options. Some functionality is exclusive to certain types of <code>SchemaType</code>s, for example only numbers support <code>min</code> and <code>max</code> values.</p>

<p>In order to customize some of these options directly from the definition of your model, set your key to an object with the format<br><code>{ type: Type, ... }</code>.</p>

<pre><code>  var Person = new Schema({
      title   : { type: String, required: true }
    , age     : { type: Number, min: 5, max: 20 }
    , meta    : {
          likes : [String]
        , birth : { type: Date, default: Date.now }
      }
  });
</code></pre>

<p>Those options are functions that are called on each SchemaType. If you want to define options later on, you could access a certain key through the <code>path</code> function:</p>

<pre><code>Person.path('age').max(400);

Person.path('meta.birth').set(function (v) {
  // this is a setter
});

Person.path('title').validate(function (v) {
  return v.length &gt; 50;
});
</code></pre>

<p>Some of the options are versatile. <code>default</code> takes a <code>Function</code> or a value. <code>validate</code> takes a <code>Function</code> or a <code>RegExp</code>. More information on these can be found in the <a href="schematypes.html">Schema Type chapter</a>.</p>

<h2>Beyond keys: Middleware</h2>

<p>Middleware are special user-defined functions that are called transparently when certain native methods are called on <code>Document</code> instances (<code>init</code>, <code>save</code> and <code>remove</code>).</p>

<p>Let's say that you want to email a certain user when his document changes. You'd then define a hook on the User schema like this:</p>

<pre><code>UserSchema.pre('save', function (next) {
  email(this.email, 'Your record has changed');
  next();
});
</code></pre>

<p>More information about the specifics of middleware can be found <a href="middleware.html">here</a>.</p>

<h2>Schema options</h2>

<p>For schema options <a href="schema-options.html">read this</a>.</p>

<h2>Instance Methods and Static methods</h2>

<p>For details about default instance methods and defining your own custom static and instance methods read <a href="methods-statics.html">this</a>.</p>

<h2>Plugins</h2>

<p>Schemas also support plugins. Read more about it on the <a href="plugins.html">Plugins</a> page.</p>

<h2>Schema events</h2>

<p>When a schema is passed to <code>mongoose.model()</code> the <code>init</code> event will be emitted on the schema, passing in the model. This is helpful for some plugins that need to hook directly into the model.</p>

<pre><code>var schema = new Schema({ name: String });

schema.on('init', function (model) {
  // do stuff with the model
});

mongoose.model('MyModel', schema);
</code></pre>
        </div>

        <div id="footer">

          <form action="http://groups.google.com/group/mongoose-orm/boxsubscribe">
           <a href="http://groups.google.com/group/mongoose-orm" id="google-subscribe-link"><img src="/docs/2.7.x/images/groups.png" border="0"></a>
           <span id="google-members-count">&nbsp;</span>
           <div id="google-subscribe-input">
             Email: <input type="text" name="email" id="google-subscribe-email">
             <input type="submit" name="go" value="Subscribe">
           </div>
          </form>

          <div>
            Mongoose by <a href="http://github.com/learnboost">LearnBoost Labs</a>.<br>
            Released under the MIT license.<br>
            Copyright <a href="http://learnboost.com">LearnBoost 2011</a>.
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
